import { Entity, Column, ManyToOne, ManyToMany, JoinColumn, JoinTable, Index } from 'typeorm';
import { BaseEntity } from '@app/common/entities/base.entity';
import { User } from './user.entity';

@Entity('blogs')
@Index(['title'])
@Index(['category'])
@Index(['status'])
@Index(['publishedAt'])
@Index(['slug'])
export class Blog extends BaseEntity {
  @Column({ type: 'varchar', length: 255 })
  title: string;

  @Column({ type: 'longtext' })
  content: string;

  @Column({ type: 'text', nullable: true })
  summary?: string;

  @Column({ type: 'varchar', length: 500, nullable: true })
  cover?: string;

  @Column({ type: 'varchar', length: 100 })
  author: string;

  @Column({ type: 'int' })
  authorId: number;

  @Column({
    type: 'enum',
    enum: ['技术', '生活', '随笔', '教程'],
    default: '技术'
  })
  category: '技术' | '生活' | '随笔' | '教程';

  @Column({ type: 'tinyint', default: 1, comment: '状态: 0=禁用, 1=启用' })
  status: number;

  @Column({ type: 'boolean', default: false })
  isTop: boolean;

  @Column({ type: 'int', default: 0 })
  viewCount: number;

  @Column({ type: 'int', default: 0 })
  likeCount: number;

  @Column({ type: 'int', default: 0 })
  commentCount: number;

  @Column({ type: 'timestamp', nullable: true })
  publishedAt?: Date | null;

  // SEO 相关字段
  @Column({ type: 'varchar', length: 255, nullable: true })
  metaTitle?: string;

  @Column({ type: 'text', nullable: true })
  metaDescription?: string;

  @Column({ type: 'varchar', length: 500, nullable: true })
  metaKeywords?: string;

  // 其他字段
  @Column({ type: 'int', nullable: true })
  readingTime?: number;

  @Column({ type: 'varchar', length: 255, nullable: true })
  slug?: string;

  @Column({ type: 'boolean', default: true })
  allowComment: boolean;

  // 软删除标记
  @Column({ type: 'boolean', default: false })
  isDeleted: boolean;

  // 作者关联
  @ManyToOne(() => User, { eager: false })
  @JoinColumn({ name: 'authorId' })
  authorUser?: User;

  // 标签关联
  @ManyToMany('Tag', 'blogs', { eager: true })
  @JoinTable({
    name: 'blog_tags',
    joinColumn: { name: 'blog_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'tag_id', referencedColumnName: 'id' }
  })
  tags: any[];

  // 虚拟属性：是否已发布
  get isPublished(): boolean {
    return this.status === 1 && !!this.publishedAt && this.publishedAt <= new Date();
  }

  // 虚拟属性：获取标签名称数组
  get tagNames(): string[] {
    return this.tags?.map(tag => tag.name) || [];
  }

  // 虚拟属性：获取预览内容
  get preview(): string {
    if (this.summary) return this.summary;
    return this.content.replace(/<[^>]*>/g, '').slice(0, 200) + '...';
  }

  // 虚拟属性：获取阅读时长（分钟）
  get estimatedReadTime(): number {
    if (this.readingTime) return this.readingTime;
    const wordsPerMinute = 200;
    const textContent = this.content.replace(/<[^>]*>/g, '');
    return Math.ceil(textContent.length / wordsPerMinute);
  }
}
